# -*- coding: utf-8 -*-
'''
Created on 05.06.2011

@author: mutius
'''

import wx
from wx._core import EVT_BUTTON
from AddColumnDialog import AddColumnDialog

class CreateTableDialog(wx.Dialog):
    def __init__(self, parent, id, cursor):
        wx.Dialog.__init__(self, parent, id)
        self.cursor = cursor
        self.description = list()
        
        self.label_3 = wx.StaticText(self, -1, u"Название таблицы")
        self.text_ctrl_2 = wx.TextCtrl(self, -1, "")
        self.static_line_2 = wx.StaticLine(self, -1)
        self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_EDIT_LABELS|wx.SUNKEN_BORDER)
        self.button_1 = wx.Button(self, -1, u"добавить поле")
        self.button_4 = wx.Button(self, -1, "Ok")

        self.SetTitle(u"создание новой таблицы")
        self.SetSize((650, 550))
        self.list_ctrl_1.InsertColumn(0,u"название поля", width = 120)
        self.list_ctrl_1.InsertColumn(1,u"тип данных", width = 110)
        self.list_ctrl_1.InsertColumn(2,u"по умолчанию", width = 120)
        self.list_ctrl_1.InsertColumn(3,u"первичный", width = 90)
        self.list_ctrl_1.InsertColumn(4,u"внешний")
        self.list_ctrl_1.InsertColumn(5,u"автоинкремент", width = 120)
 
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.label_3, 0, wx.ALL, 10)
        sizer_2.Add(self.text_ctrl_2, 0, wx.ALL|wx.EXPAND, 10)
        sizer_2.Add(self.static_line_2, 0, wx.ALL|wx.EXPAND, 5)
        sizer_2.Add(self.list_ctrl_1, 7, wx.ALL|wx.EXPAND, 5)
        sizer_3.Add(self.button_1, 0, wx.ALL, 5)
        sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
        sizer_2.Add(self.button_4, 0, wx.ALL|wx.ALIGN_RIGHT, 5)
        self.SetSizer(sizer_2)
        self.Layout()
        
        self.Bind(EVT_BUTTON, self.onAddString, self.button_1)
        self.Bind(EVT_BUTTON, self.onOk, self.button_4)
   
    def onAddString(self, event):
        print "add"
        dialog = AddColumnDialog(None, -1, self.cursor)
        dialog.ShowModal()
        if(len(dialog.returnedData.keys()) != 0):
            self.description.append(dialog.returnedData)
            pos = self.list_ctrl_1.InsertStringItem(0, dialog.returnedData["name"])
            self.list_ctrl_1.SetStringItem(pos, 1, dialog.returnedData["type"])
            self.list_ctrl_1.SetStringItem(pos, 2, str(dialog.returnedData["default"]))
            self.list_ctrl_1.SetStringItem(pos, 3, str(dialog.returnedData["primary"]))
            self.list_ctrl_1.SetStringItem(pos, 4, str(dialog.returnedData["foreign"]))
            self.list_ctrl_1.SetStringItem(pos, 5, str(dialog.returnedData["autoincrement"]))
        dialog.Destroy()
    
    def onOk(self, event):
        name = self.text_ctrl_2.GetValue()
        #print "ok pushed"
        if len(name) == 0:
            message = wx.MessageDialog(None, u"некорректное название", u"Message", wx.ICON_HAND)
            message.ShowModal()
            message.Destroy()
        elif self.list_ctrl_1.GetItemCount() == 0:
            message = wx.MessageDialog(None, u"необходимо добавить хотя бы одно поле", u"Message", wx.ICON_WARNING)
            message.ShowModal()
            message.Destroy()
        else:
            print "ok"
            print self.description
            command = u"CREATE TABLE "+ name + u"("
            for item in self.description:
                subcommand = item["name"] + " " + item["type"] + " "
                if item["default"] != None:
                    subcommand = subcommand + "DEFAULT " + item["default"] + " "
                if item["autoincrement"] == True:
                    subcommand = subcommand + "AUTO_INCREMENT "
                command = command + subcommand + ","
            for item in self.description:
                subcommand = u"FOREIGN KEY ("
                if item['foreign'] == True:
                    subcommand = subcommand + item["name"] + ") REFERENCES " + item["references_table"] +  "(" + item["references_column"] + "),"
                    command = command + subcommand
            subcommand = str()
            for item in self.description:
                if item['primary'] == True:
                    subcommand = subcommand + item["name"] + ","
            if len(subcommand) != 0:
                subcommand = u"PRIMARY KEY (" + subcommand[0:-1] + "),"
                command = command + subcommand
            command = command[0:-1] + ")"
            print command
            try:
                self.cursor.execute(command)
            except:
                message = wx.MessageDialog(None, u"неудалось создать таблицу", u"Message", wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
            self.Close()
